%% Copyright (C) 2012 Fisher–Yates
%% 
%% This program is free software; you can redistribute it and/or modify
%% it under the terms of the GNU General Public License as published by
%% the Free Software Foundation; either version 2 of the License, or
%% (at your option) any later version.
%% 
%% This program is distributed in the hope that it will be useful,
%% but WITHOUT ANY WARRANTY; without even the implied warranty of
%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%% GNU General Public License for more details.
%% 
%% You should have received a copy of the GNU General Public License
%% along with Octave; see the file COPYING.  If not, see
%% <http://www.gnu.org/licenses/>.

%% shuffle(x)
%% Retorna um vetor y que é o vetor x embaralhado.

%% Author: Fisher–Yates <https://secure.wikimedia.org/wikipedia/en/wiki/Fisher–Yates_shuffle>
%% Created: 2012-03-26

function y=shuffle(x)

  global DEBUG 
  if ~exist('DEBUG', 'var'),
    DEBUG = 0;
  end

  n = length(x); y = x;

  while n > 1,
    
    k = floor(1 + n*rand(1)); %# returns 1 <= k <= n
    if k ~= n,
      if DEBUG,
	printf('Shuffling %d with %d\n', k, n);
	printf('Before\n'); disp(y);
      end
      dummy = y(n);
      y(n) = y(k);
      y(k) = dummy;
      if DEBUG,
	printf('After\n'); disp(y);
      end
    else
      if DEBUG,
	printf('Skipping %d\n', n);
      end
    end
    n = n-1;
  
  end

end
